#pragma once
#include "hge.h"  
#include "hgeSprite.h"  
#include<iostream>
using namespace std;
#include"Map.h"
#include"Role.h"
class ObjectManager{
public:
	HGE			*m_phge;
	int			RoleNum;
	int			currentRole;
	Map*		m_map;
	Role*		m_role[4];
	int nowMapX,nowMapY;

	int VX,VY;
	int SX,SY;
	bool reSelect;
	string picName;
	ObjectManager(HGE* phge){
		m_phge=phge;
		m_map=new Map(phge);
		RoleNum=0;
		currentRole=0;
		nowMapX=64*12;
		nowMapY=64*15;

		reSelect=false;
		picName="space.png";
	}
	hgeSprite* getPic(const char* url){
		return new hgeSprite(m_phge->Texture_Load(url),0,0,128,64);
	}
	Role*	nowRole(){
		return m_role[currentRole];
	}
	Role*	GetRoleByOrder(int n){
		return m_role[n];
	}
	void update(){
		for(int i=0;i<RoleNum;i++)
			m_role[i]->update(nowMapX,nowMapY);
		m_map->update(nowMapX,nowMapY);
		inverst_select();
	}
	void addRole(Role* r){
		m_role[RoleNum]=r;
		RoleNum++;
	}
	void Render(){
		m_map->Render();
		for(int i=0;i<RoleNum;i++)
			m_role[i]->Render();
		if(reSelect)
			getPic(picName.c_str())->Render(SX-64,SY-32);
	}
	void setReselectPic(string pic){
		picName=pic;
	}
	void MapFocusOn(int n){
		nowMapX=m_map->getRoad(n)->mapX-448;
		nowMapY=m_map->getRoad(n)->mapY-320;
	}
	void PutRoleOnMap(Role* r,int n){
		int dx,dy;
		int roleDirection=0;
		r->PosNum=n;
		r->virX=m_map->getRoad(n)->virX;
		r->virY=m_map->getRoad(n)->virY;
		if(!r->abState.clockwise){
			dx=(m_map->getRoad(n+1)->mapX-m_map->getRoad(n)->mapX)/16;
			dy=(m_map->getRoad(n+1)->mapY-m_map->getRoad(n)->mapY)/16;
		}
		else{
			dx=(m_map->getRoad(n-1)->mapX-m_map->getRoad(n)->mapX)/16;
			dy=(m_map->getRoad(n-1)->mapY-m_map->getRoad(n)->mapY)/16;
		}
		if(dx>0&&dy>0)
			roleDirection=2;
		if(dx>0&&dy<0)
			roleDirection=1;
		if(dx<0&&dy<0)
			roleDirection=0;
		if(dx<0&&dy>0)
			roleDirection=3;
		r->createSpr(0,roleDirection);
	}
	void inverst_select(){
		float x,y;
		m_phge->Input_GetMousePos(&x,&y);
		x+=nowMapX-9*64;
		x=x/64;
		y+=nowMapY-20*64;
		y=y/32;
		VX=int((x-y)/2+0.5);
		VY=int((x+y)/2+0.5);
		int mapX=9*64+64*VX+64*VY;
		int mapY=20*64+32*VY-32*VX;
		SX=mapX-nowMapX;
		SY=mapY-nowMapY;
	}
	int getRoadByXY(int x,int y){
		for(int i=0;i<m_map->RoadLength;i++){
			if(m_map->getRoad(i)->virX==x && m_map->getRoad(i)->virY==y)
				return i;
		}
		return -1;
	}
};